package com.ctgu.tengyun.util;

import com.ctgu.tengyun.exception.ConvertException;
import com.ctgu.tengyun.exception.RequestValidateException;
import org.apache.commons.codec.digest.DigestUtils;

public class MixedStrUtil {

	private final static String secretKey = "ctgutengyun";

	public static String encode(String rawString) {
		String md5 = DigestUtils.md5Hex(rawString);
		return MixedEncryption.encode(secretKey, md5, rawString);
	}

	public static String decode(String encodedStr) {
		try {
			String[] strs = MixedEncryption.decode(encodedStr, secretKey);
			if (strs.length == 2) {
				if (strs[0].equals(DigestUtils.md5Hex(strs[1]))) {
					return strs[1];
				} else {
					throw new ConvertException("decode string fail" + ", md5Str:" + strs[0] + ", rawStr:" + strs[1], "decode string fail");
				}
			}
		} catch (RuntimeException ex) {
			throw new ConvertException("decode string fail, str:" + encodedStr, "decode string fail", ex);
		}
		throw new ConvertException("decode string fail, str:" + encodedStr, "decode string fail");
	}

	public static final String decodeWithValidateEx(String encodedStr) {
		try {
			if(StringUtils.isEmpty(encodedStr)){
				throw new RequestValidateException("decode fail, str:" + encodedStr);
			}
			return decode(encodedStr);
		} catch (RuntimeException ex) {
			throw new RequestValidateException(ex.getMessage(), ex);
		}
	}
}